package com.gc.ordersys2.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gc.ordersys2.entity.Cart;
import com.gc.ordersys2.entity.OrderDetail;
import com.gc.ordersys2.entity.Ordered;
import com.gc.ordersys2.mapper.CartMapper;
import com.gc.ordersys2.mapper.OrderDetailMapper;
import com.gc.ordersys2.mapper.OrderedMapper;
import com.gc.ordersys2.service.IOrderedService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cuijianhao
 * @since 2024-09-05
 */
@Service
public class OrderedServiceImpl extends ServiceImpl<OrderedMapper, Ordered> implements IOrderedService {
    @Autowired(required = false)
    CartMapper cartMapper;
    @Autowired(required = false)
    OrderedMapper orderMapper;
    @Autowired(required = false)
    OrderDetailMapper orderDetailMapper;



    @Override
    public boolean submit(Integer deskId) {
        //0.插入要结算的餐桌对应的订单信息
        Cart cart = new Cart();
        cart.setDeskId(deskId);
        List<Cart> list = cartMapper.getList(cart);

        //1.向订单表中插入订单数据
        double total = 0;
        for(Cart c : list){
            total += c.getPrice()*c.getNum();
        }
        Ordered orders = new Ordered();
        orders.setOrderTime(new Date());
        orders.setTotal(total);
        orders.setDid(deskId);
        orderMapper.insert(orders);

        OrderDetail od = new OrderDetail();
        //2.向明细表中插入 明细数据 (暂定，这里可以更优雅)
        for(Cart c : list){
            od.setOrderId(orders.getId());
            od.setProImg(c.getProimg());
            od.setNum(c.getNum());
            od.setProPrice(c.getPrice());
            od.setProName(c.getPname());
            orderDetailMapper.insert(od);
        }

        //3.将结算过的桌的菜品从购物车中删除
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("desk_id",cart.getDeskId());
        cartMapper.delete(queryWrapper);


        return true;
    }
}
